import React from 'react'
import { Row, Col, Select, InputNumber, Switch, Icon } from 'antd'
import { AdvancedSearch } from 'components'
import moment from 'moment'
const Option = Select.Option;

class MoneyInput extends React.Component {

  constructor(props) {
    super(props);
    const value = props.value || {};
    this.state = {
      currency: value.currency || null,
      money: value.money || 0
    }
  }

  componentWillReceiveProps(nextProps) {
    if('value' in nextProps) {
      const value = nextProps.value;
      if(value)
        this.setState({
          currency: value.currency || null,
          money: value.money || 0
        });
      else
        this.setState({
          currency: null,
          money: 0
        })
    }
  }

  onChange = value => {
    const { onChange } = this.props;
    onChange && onChange(Object.assign({}, value));
  };

  onChangeValue = (value, attr) => {
    this.setState({ [attr]: value }, () => {
      this.onChange(this.state);
    });
  };

  render() {
    const { currency, money } = this.state;
    return (
      <Row>
        <Col span={15}>
          <Select
            value={currency}
            onChange={value => this.onChangeValue(value, 'currency')}
          >
            <Option key='CNY'>人民币</Option>
            <Option key='USD'>美元</Option>
          </Select>
        </Col>
        <Col span={9}>
          <InputNumber
            style={{ width: '100%' }}
            value={money}
            onChange={value => this.onChangeValue(value, 'money')}
          />
        </Col>
      </Row>
    )
  }

}

export default {
  key: 'advanced-search',
  name: 'AdvancedSearch 高级搜索',
  author: '张然',
  description: '比::SearchArea::高级一点的搜索。',
  isExampleFull: true,
  api: [
    {
      title: 'API',
      data: [{
        param: 'title', description: '标题。', type: 'string|ReactNode', defaultValue: '-'
      }, {
        param: 'searchForm', description: '搜索项配置，见下方::searchItem::。', type: 'searchItem[]', defaultValue: '-'
      }, {
        param: 'onSearch', description: '点击搜索的回调。', type: 'function(value)', defaultValue: '-'
      }, {
        param: 'onReset', description: '点击重置的回调。', type: 'function', defaultValue: '-'
      }, {
        param: 'showFilterTags', description: '是否显示筛选标签列表。', type: 'bool', defaultValue: 'true'
      }, {
        param: 'renderCollapseText', description: '展开按钮的内容。', type: 'function(number, collapsed)', defaultValue: <span><Icon type="filter" />&nbsp;高级搜索(number)</span>
      }, {
        param: 'popoverTitle', description: '弹窗标题。', type: 'string|ReactNode', defaultValue: '高级搜索'
      }, {
        param: 'searchButton', description: '搜索按钮的配置，当设置为false时，按钮不显示；当设置为字符串时，为按钮的文字；当设置为对象时，见下方::buttonProps::。', type: 'bool|string|buttonProps', defaultValue: '{ props: { type: \'primary\' }, text: \'搜索\' }'
      }, {
        param: 'resetButton', description: '重置按钮的配置，同上。', type: 'bool', defaultValue: '重置'
      }, {
        param: 'pinnedList', description: '默认展开条件列表的::id::数组。', type: 'array', defaultValue: '[]'
      }, {
        param: 'onChangePinnedList', description: '当默认展开条件列表变更时的回调。', type: 'function(ids)', defaultValue: '() => {}'
      }, {
        param: 'tableName', description: '当设置此值时，将会增加条件列表设置、默认展开项保存功能，这些功能都有对应后台交互，使用时请注意，有业务需求再增加此字段。如果设置，请保证全项目唯一。', type: 'string|ReactNode', defaultValue: '高级搜索'
      }],
      description: ''
    },
    {
      title: 'searchItem',
      data: [{
        param: 'id', description: '返回数据时的字段名。', type: 'string', defaultValue: '-'
      }, {
        param: 'label', description: '搜索项的标题。', type: 'string|ReactNode', defaultValue: '-'
      }, {
        param: 'component', description: '显示的组件类型，除了几个内置的数据类型外，还可以注入自定义::表单组件::，该表单值同样会返回在::onSearch::中；当::extra::为::true::时，可注入任何组件，该内部所有组件值::onSearch::不会返回。', type: 'string|ReactNode', defaultValue: '-'
      }, {
        param: 'extra', description: '是否是额外注入非表单组件。', type: 'bool', defaultValue: '-'
      }, {
        param: 'props', description: '内部显示组件需要的参数。', type: 'object', defaultValue: '-'
      }, {
        param: 'initialValue', description: '初始值。', type: 'any', defaultValue: '-'
      }, {
        param: 'parser', description: '自定义返回数据所需要的格式，参数方法中参数为组件的::value::，返回值为一个对象，该对象将通过::Object.assign::注入到::onSearch::的结果中，如果该对象里没有与::id::相同的字段，则自动删除返回数据中的::id::字段。', type: 'value => object', defaultValue: '-'
      }, {
        param: 'tagParser', description: '自定义显示在上方筛选标签中的显示字段所需要的格式，参数方法中参数为组件的::value::，返回值为显示在标签内的字符串。', type: 'value => string', defaultValue: '内置类型已有对应的转换，其余无'
      }, {
        param: 'decorator', description: '需要表单校验时，此参数为::getFieldDecorator::方法的第二个参数。', type: 'object', defaultValue: '-'
      }, {
        param: 'hasValue', description: '判断值是否存在，如果该方法返回true则会在下方搜索标签内显示。', type: 'function(field, value)', defaultValue: 'value => (value instanceof Array) ? value.length > 0 : value'
      }, {
        param: 'JSONFormatter', description: '当设置了::tableName::时有用，因为条件列表存在后台的值只能为JSON，组件内已经对内置组件做过了全量的JSON判断，如果需要自定义组件的JSON方法，请设置为此值。', type: 'function(value, hasValue)', defaultValue: '-'
      }, {
        param: 'JSONParser', description: '当设置了::tableName::时有用，当从后台拿到存入的JSON值后，组件内已经对内置组件做过了全量的JSON.parse判断，如果需要自定义转化为此组件需要的值的规则，请设置此值。', type: 'function(jsonValue)', defaultValue: '-'
      }, {
        param: 'JSONObjectFormatterParams', description: '当设置了::tableName::时有用，当把::object::或由::object::组成的::array::值JSON化存在后台时，往往考虑性能不需要存入对象的所有值，只存需要的几个值，这个值就是需要存值的字段名数组。主要用于内置的::Selector::、::Chooser::、::Searcher::值的处理。', type: 'array', defaultValue: '-'
      }],
      description: ''
    },
    {
      title: 'buttonProps',
      data: [{
        param: 'text', description: '按钮的文字。', type: 'string', defaultValue: '-'
      }, {
        param: 'props', description: '按钮组件所需要的参数。', type: 'object', defaultValue: '-'
      }],
      description: ''
    },
    {
      title: 'topLevel API',
      data: [{
        param: 'getFormById', description: '根据::id::在::searchForm::内查找对应的表单项', type: 'function(id, searchForm)', defaultValue: '-'
      }, {
        param: 'setFormByItem', description: '根据::item::的::id::替换::serachForm::内对应的表单项', type: 'function(searchFormItem, searchForm)', defaultValue: '-'
      }],
      description: '::AdvancedSearch::内置了两个静态方法，方便在进行级联和项目更改时进行操作。'
    }
  ],
  example: [
    {
      title: '基础用法',
      description: '几种内置的基本类型，参数可通过::props::传入。',
      state: {

      },
      getMethod: context => {
        return {}
      },
      getContent: context => {
        const {} = context.state;
        const { user } = context.props;
        return (
          <div>
            <AdvancedSearch
              onSearch={console.log}
              title='基本用法'
              searchForm={[
                {
                  id: 'test1', label: 'Input', component: 'Input',
                  props: {
                    placeholder: '请输入'
                  }
                }, {
                  id: 'test2', label: 'DatePicker', component: 'DatePicker',
                }, {
                  id: 'test3', label: 'Chooser', component: 'Chooser',
                  props: {
                    type: 'user',
                    valueKey: 'userOID',
                    labelKey: 'fullName'
                  }
                }, {
                  id: 'test4', label: 'Selector', component: 'Selector',
                  props: {
                    type: 'currency',
                    params: { language: 'chineseName', userOID: user.userOID },
                    filter: item => item.enable,
                    showSearch: true
                  }
                }, {
                  id: 'test5', label: 'Searcher', component: 'Searcher',
                  props: {
                    type: 'department',
                    labelKey: 'path',
                    listExtraParams: { flag: 1002 },
                    onlyNeed: 'departmentOID'
                  }
                }, {
                  id: 'test6', label: 'Inputter', component: 'Inputter',
                  props: {
                    type: 'user',
                    valueKey: 'fullName'
                  }
                }, {
                  id: 'test7', label: 'DateRangePicker', component: 'DateRangePicker'
                }]
              }
            />
          </div>
        )
      }
    },
    {
      title: '默认值',
      description: '通过::initialValue::增加默认值。',
      state: {

      },
      getMethod: context => {
        return {}
      },
      getContent: context => {
        const {} = context.state;
        const { user } = context.props;
        return (
          <div>
            <AdvancedSearch
              onSearch={console.log}
              title='默认值'
              searchForm={[
                {
                  id: 'test1', label: '输入框', component: 'Input',
                  initialValue: '啦啦啦'
                }, {
                  id: 'test2', label: '日期及自定义输出', component: 'DatePicker',
                  initialValue: moment()
                }, {
                  id: 'test3', label: 'Chooser', component: 'Chooser',
                  initialValue: [{ userOID: 'GangDan', fullName: '王钢蛋' }],
                  props: {
                    type: 'user',
                    valueKey: 'userOID',
                    labelKey: 'fullName'
                  }
                }, {
                  id: 'test4', label: 'Selector', component: 'Selector',
                  initialValue: { currencyName: '人民币', currency: 'CNY' },
                  props: {
                    type: 'currency',
                    params: { language: 'chineseName', userOID: user.userOID },
                    filter: item => item.enable,
                    showSearch: true
                  }
                }, {
                  id: 'test5', label: 'Searcher', component: 'Searcher',
                  initialValue: [{ path: '李二狗', departmentOID: 'ErGou' }, { path: '王钢蛋', departmentOID: 'GangDan' }],
                  props: {
                    type: 'department',
                    labelKey: 'path',
                    listExtraParams: { flag: 1002 },
                    onlyNeed: 'departmentOID'
                  }
                }, {
                  id: 'test6', label: 'Inputter', component: 'Inputter',
                  initialValue: '马飞飞',
                  props: {
                    type: 'user',
                    valueKey: 'fullName'
                  }
                }, {
                  id: 'test7', label: 'DateRangePicker', component: 'DateRangePicker',
                  initialValue: [moment().subtract(1, 'month'), moment()]
                }]
              }
            />
          </div>
        )
      }
    },
    {
      title: '组件注入和数据转换',
      description: '如果内置类型无法满足，则可以通过::component::注入表单组件，设置::extra::可注入非表单组件。同时所有的表单组件返回值都可以通过::parser::进行自定义转换',
      state: {

      },
      getMethod: context => {
        return {}
      },
      getContent: context => {
        const {} = context.state;
        return (
          <div>
            <AdvancedSearch
              onSearch={console.log}
              title='组件注入和数据转换'
              searchForm={[
                {
                  id: 'test0', label: '日期数据转换', component: 'DatePicker',
                  initialValue: moment(),
                  parser: value => ({
                    date: value ? value.format('YYYY-MM-DD') : null
                  })
                },
                {
                  id: 'test1', label: '自定义表单组件', component: <MoneyInput />,
                  initialValue: {
                    currency: 'CNY',
                    money: 0
                  },
                  parser: value => ({
                    currency: value.currency,
                    number: value.money
                  }),
                  tagParser: value => `${value.currency} ${value.money}`
                }, {
                  id: 'test2', label: 'Chooser数据转换', component: 'Chooser',
                  initialValue: [{ userOID: 'GangDan', fullName: '王钢蛋' }],
                  props: {
                    type: 'user',
                    valueKey: 'userOID',
                    labelKey: 'fullName'
                  },
                  parser: value => ({
                    userList: value.map(user => user.fullName).join(',')
                  })
                }, {
                  id: 'test3', label: '自定义非表单组件', extra: true, component: <span>静态文字</span>
                }]
              }
            />
          </div>
        )
      }
    },
    {
      title: '数据变更和级联',
      description: '使用::getForm::即可获得组件内部的表单对象，直接操作传入的::searchForm::即可实时调整属性。',
      state: context => ({
        searchForm: [
          {
            id: 'test1', label: '是否禁用输入框', component: <Switch onChange={context.onChangeSwitch}/>,
            decorator: {
              valuePropName: 'checked'
            }
          }, {
            id: 'test2', label: '给输入框赋值', component: 'Select', props: {
              onChange: context.onChangeSelect
            },
            children: [{
              label: '张二狗', value: '张二狗'
            }, {
              label: '王钢蛋', value: '王钢蛋'
            }].map(item => <Option key={item.value}>{item.label}</Option>)
          }, {
            id: 'test3', label: '输入框', component: 'Input', props: {}
          }
        ]
      }),
      getMethod: context => {
        return {
          onChangeSwitch: checked => {
            const { searchForm } = context.state;
            let formItem = AdvancedSearch.getFormById('test3', searchForm);
            formItem.props.disabled = checked;
            context.setState({ searchForm: AdvancedSearch.setFormByItem(formItem, searchForm) })
          },
          onChangeSelect: (value) => {
            context.form.setFieldsValue({ 'test3': value });
          }
        }
      },
      getContent: context => {
        const { searchForm } = context.state;
        return (
          <div>
            <AdvancedSearch
              onSearch={console.log}
              title='数据变更和级联'
              getForm={form => context.form = form}
              searchForm={searchForm}
            />
          </div>
        )
      }
    },
    {
      title: '表单校验和按钮自定义',
      description: '表单相关校验可通过::decorator::传入，按钮也可以自定义。',
      state: {

      },
      getMethod: context => {
        return {}
      },
      getContent: context => {
        const {} = context.state;
        const { user } = context.props;
        return (
          <div>
            <AdvancedSearch
              onSearch={console.log}
              showFilterTags={false}
              title='表单校验和按钮自定义'
              searchButton='新建'
              renderCollapseText={() => <span>新建人员<Icon type="plus" /></span>}
              popoverTitle='新建人员'
              resetButton={{
                text: '清空',
                props: {
                  type: 'danger'
                }
              }}
              searchForm={[
                {
                  id: 'name', label: '姓名', component: 'Input',
                  props: {
                    placeholder: '请输入姓名'
                  },
                  decorator: {
                    rules: [{
                      required: true,
                      message: '姓名必填'
                    }]
                  }
                }, {
                  id: 'phone', label: '手机号', component: 'Input',
                  props: {
                    placeholder: '请输入手机号'
                  },
                  decorator: {
                    rules: [{
                      required: true,
                      message: '手机号必填'
                    }, {
                      pattern: "^(13[0-9]|14[579]|15[0-3,5-9]|16[6]|17[0135678]|18[0-9]|19[89])\\d{8}$",
                      message: '请输入正确的手机号'
                    }]
                  }
                }, {
                  id: 'marry', label: '是否已婚', component: <Switch/>,
                  decorator: {
                    valuePropName: 'checked'
                  }
                }]
              }
            />
          </div>
        )
      }
    },
  ]
}
